#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <mutex>
#include <cassert>
#include <fstream>
#include <jsoncpp/json/json.h>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <sstream>
#include <iomanip>

#include "../comm/util.hpp"
#include "../comm/log.hpp"
#include "oj_model_mq.hpp"
#include "../comm/httplib.h"
#include "oj_view.hpp"

namespace ns_control
{
    using namespace std;
    using namespace ns_view;
    using namespace ns_log;
    using namespace ns_model;
    using namespace ns_util;
    using namespace httplib;
    using namespace boost::asio;
    using namespace boost::beast;

    // 提供服务的主机
    class Machine
    {
    public:
        std::string ip;
        int port;
        uint64_t load;   // 编译服务的负载
        std::mutex *mtx; 

    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}

        void IncLoad()
        {
            if (mtx)
                mtx->lock();
            load++;
            if (mtx)
                mtx->unlock();
        }

        void DecLoad()
        {
            if (mtx)
                mtx->lock();
            load--;
            if (mtx)
                mtx->unlock();
        }

        void ResetLoad()
        {
            if (mtx)
                mtx->lock();
            load = 0;
            if (mtx)
                mtx->unlock();
        }

        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();

            return _load;
        }
    };

    const std::string service_machines = "./conf/service_machine.conf";
    // 负载均衡模块
    class LoadBalence
    {
    private:
        std::vector<Machine> machines; // 可以提供编译服务的所有主机
        std::vector<int> online;       // 在线主机
        std::vector<int> offline;      // 离线主机
        std::mutex mtx;               

    public:
        LoadBalence()
        {
            assert(LoadConf(service_machines));
            LOG(INFO) << "加载" << service_machines << "成功" << "\n";
        }
        ~LoadBalence() {}

        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载" << machine_conf << "失败" << "\n";
                return false;
            }

            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分" << line << "失败" << "\n";
                    continue;
                }
                Machine m;
                m.ip = tokens[0];
                m.port = atoi(tokens[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();

                online.push_back(machines.size()); 
                machines.push_back(m);
            }

            in.close();
            return true;
        }

        bool SmartChoice(int *id, Machine **m)
        {
            // 1、使用选择好的主机（更新对应主机的负载load）
            // 2、可能需要离线当前主机
            mtx.lock();

            // 简易负载均衡算法：轮询+hash
            int online_num = online.size();
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "所有后端编译主机离线，请立即查看" << "\n";
                return false;
            }

            // 遍历寻找负载最小的machine
            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].Load();
            for (int i = 0; i < online_num; i++)
            {
                uint64_t cur_load = machines[online[i]].Load();
                if (min_load > cur_load)
                {
                    min_load = cur_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }
            mtx.unlock();
            return true;
        }

        void OfflineMachines(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[which].ResetLoad();
                    online.erase(iter);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }

        void OnlineMachines()
        {
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();

            LOG(INFGO) << "所有主机均已上线" << "\n";
        }

        // for test
        void ShowMachines()
        {
            mtx.lock();
            std::cout << "当前在线主机列表: ";
            for (auto &id : online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;

            std::cout << "当前离线主机列表: ";
            for (auto &id : offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;

            mtx.unlock();
        }
    };

    // 这是核心业务逻辑控制器
    class Control
    {
    private:
        Model _model;              // 提供数据
        View _view;                // 提供网页渲染功能
        LoadBalence load_balance_; // 核心负载均衡器

    public:
        Control() {}
        ~Control() {}

    public:
        void RecoveryMachines()
        {
            load_balance_.OnlineMachines();
        }

        // 根据题目数据构建网页
        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<struct Question> all;
            if (_model.GetAllQuestions(&all))
            {
                sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2)
                     { return atoi(q1.number.c_str()) < atoi(q2.number.c_str()); });
                // 获取题目信息成功，将其构建为html网页
                _view.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题目失败、形成题目列表失败";
                ret = false;
            }
            return ret;
        }

        // 根据题目数据构建网页
        bool Question(const string &number, string *html)
        {
            struct Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                // 获取指定题目信息成功，将其构建为html网页
                _view.OneExpandHtml(q, html);
            }
            else
            {
                *html = "获取指定题目: " + number + "失败";
                return false;
            }
            return true;
        }

        void Judge(const std::string &number, const std::string &in_json, std::string *out_json)
        {
            // 0、根据题号，拿到对应的题目细节
            struct Question q;
            _model.GetOneQuestion(number, &q);

            // 1、对in_json进行反序列化，得到提交的代码
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            // 2、重新拼接用户提交代码+测试用例代码，形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);

            // 3、选择负载最低的服务器
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!load_balance_.SmartChoice(&id, &m))
                {
                    break;
                }

                LOG(INFO) << "选择主机成功, 主机id: " << id << "详情: " << m->ip << " : " << m->port << "\n";

                // 4、发送http请求，得到结果
                Client cli(m->ip, m->port);
                m->IncLoad();
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {

                    // 5、将结果赋值给 *out_json，返回给用户
                    if (res->status == 200)
                    {
                        (*out_json) = res->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译与运行服务成功" << "\n";
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    LOG(ERROR) << "当前请求的主机id: " << id << "详情: " << m->ip << " : " << m->port << "可能已经离线" << "\n";
                    load_balance_.OfflineMachines(id);
                    //load_balance_.ShowMachines(); // 仅用于测试
                }
            }
        }
    };
}
